import { useEffect, useState } from "react"
import { Link, useNavigate } from "react-router-dom"
import { observer } from "mobx-react"

import { Table, Tag, Space, Card, Breadcrumb, Form, Button, Radio, DatePicker, Select } from "antd"
import { EditOutlined, DeleteOutlined } from "@ant-design/icons"

import { articleList, articleDel } from "@/api/main/article"
import { useStore } from "@/store"

import img404 from "@/assets/error.png"

const { Option } = Select
const { RangePicker } = DatePicker

const Article = () => {
  const { channelStore } = useStore()

  const [form] = Form.useForm()

  const [articleData, setArticleData] = useState({
    list: [],
    count: 0
  })

  const [params, setParams] = useState({
    page: 1,
    per_page: 10
  })

  // 获取文章列表
  useEffect(() => {
    const loadList = async () => {
      const res = await articleList(params)
      const { results, total_count } = res.data
      setArticleData({
        list: results,
        count: total_count
      })
    }
    loadList()
  }, [params])

  // 数据处理
  const onFinish = values => {
    const { status, channel_id, date } = values

    const _params = {
      status,
      channel_id,
      begin_pubdate: date && date[0].format("YYYY-MM-DD"),
      end_pubdate: date && date[1].format("YYYY-MM-DD")
    }

    setParams({ ...params, ..._params })
  }
  // 翻页实现
  const pageChange = page => {
    setParams({ ...params, page })
  }

  const formatStatus = type => {
    const TYPES = {
      1: <Tag color="red">审核失败</Tag>,
      2: <Tag color="green">审核成功</Tag>
    }
    return TYPES[type]
  }

  // 编辑文章
  const navigate = useNavigate()
  const goPublish = data => {
    navigate(`/publish?id=${data.id}`)
  }

  // 删除文章
  const delArticle = async data => {
    await articleDel(data.id)
    setParams({ ...params, page: 1 })
  }

  const columns = [
    {
      title: "封面",
      dataIndex: "cover",
      width: 150,
      render: cover => {
        return <img src={cover.images[0] || img404} width={80} height={60} alt="" />
      }
    },
    { title: "标题", dataIndex: "title", width: 220 },
    {
      title: "状态",
      dataIndex: "status",
      render: data => formatStatus(data)
    },
    { title: "发布时间", dataIndex: "pubdate", width: 200 },
    { title: "阅读数", dataIndex: "read_count", width: 180 },
    { title: "评论数", dataIndex: "comment_count", width: 180 },
    { title: "点赞数", dataIndex: "like_count", width: 180 },
    {
      title: "操作",
      fixed: "right",
      render: data => {
        return (
          <Space size="middle">
            <Button type="primary" shape="circle" icon={<EditOutlined />} onClick={() => goPublish(data)} />
            <Button type="primary" danger shape="circle" icon={<DeleteOutlined />} onClick={() => delArticle(data)} />
          </Space>
        )
      }
    }
  ]

  return (
    <div>
      <Card
        title={
          <Breadcrumb separator="/">
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>内容管理</Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        <Form form={form} labelCol={{ span: 2 }} wrapperCol={{ span: 22 }} initialValues={{ status: undefined }} onFinish={onFinish}>
          <Form.Item label="状态" name="status">
            <Radio.Group>
              <Radio value={undefined}>全部</Radio>
              <Radio value={0}>草稿</Radio>
              <Radio value={1}>待审核</Radio>
              <Radio value={2}>审核通过</Radio>
              <Radio value={3}>审核失败</Radio>
            </Radio.Group>
          </Form.Item>

          <Form.Item label="频道" name="channel_id">
            <Select placeholder="请选择文章频道" style={{ width: 200 }}>
              {channelStore.typeList.map(channel => (
                <Option key={channel.key} value={channel.key}>
                  {channel.value}
                </Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item label="日期" name="date">
            <RangePicker></RangePicker>
          </Form.Item>

          <Form.Item label=" " colon={false}>
            <Button htmlType="button" onClick={() => form.resetFields()}>
              重置
            </Button>
            <Button type="primary" htmlType="submit" style={{ margin: "0 8px" }}>
              查询
            </Button>
          </Form.Item>
        </Form>

        <Table
          rowKey="id"
          columns={columns}
          dataSource={articleData.list}
          bordered
          pagination={{
            current: params.page,
            pageSize: params.per_page,
            total: articleData.count,
            showSizeChanger: true,
            showTotal: total => `共 ${total} 条数据`,
            onChange: pageChange
          }}
        />
      </Card>
    </div>
  )
}

export default observer(Article)
